// pages/hetong/hetong.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    typeShow: false,
    utype: 1,
    show: false,
    LinkName: '',
    ComName: ''
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(!app.checkFjLogin()){
      wx.reLaunch({
        url: '/pages/login/index?forceSource=/packageB/pages/hetong/hetong'
      });
    }else{
      this.getUserInfo()
    }
  },

  // 获取用户姓名与签署状态
  getUserInfo(){
    wx.showLoading({
      mask: true
    })
    const url = 'api/FeijiuApp/Feijiu_HeZuo_GetUserInfo'
    const LoginUID = wx.getStorageSync('FjLoginLog').UID
    const _this=this
    app.getDaoPostN(url, {LoginUID},function(r){
      if(r.code == 200){
        wx.hideLoading();
        if(r.data == '1'){
          _this.setData({
            show: true,
          })
        } else {
          _this.setData({
            typeShow: true,
            LinkName: r.data.LinkName,
            ComName: r.data.ComName
          })
        }
      }else{
        wx.hideLoading();
        wx.showToast({
          title: r.message,
          icon:'none'
        })
      }
    })
  },

  // 签约主体
  typeChange(e){
    this.setData({
      utype: e.detail.value,
    })
  },
  bindLinkblur(e){
    this.setData({
      LinkName: e.detail.value
    })
  },
  bindComblur(e){
    this.setData({
      ComName: e.detail.value
    })
  },
  cancel(){
    wx.switchTab({
      url: '/pages/index/index'
    });
  },
  
  // 关闭弹窗
  onClose(){
    this.setData({
      show: false
    })
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  // 去签约合同
  setContract(){
    const {utype, LinkName, ComName} = this.data
    if(utype == 1 && !LinkName){
      return wx.showToast({
        title: '姓名不能为空',
        icon:'none'
      })
    } else if (utype == 2 && (!LinkName || !ComName)){
      return wx.showToast({
        title: '名称不能为空',
        icon:'none'
      })
    }
    this.setContractStart()
  },

  // 发起签署合同
  setContractStart(){
    wx.showLoading({
      mask: true
    })
    const url = 'api/FeijiuApp/Feijiu_HeZuo_CreateContract'
    const LoginUID = wx.getStorageSync('FjLoginLog').UID
    const _this=this
    let params;
    if(this.data.utype == 1){
      params = {
        LoginUID,
        utype: this.data.utype,
        LinkMan: this.data.LinkName,
      }
    } else {
      params = {
        LoginUID,
        utype: this.data.utype,
        LinkMan: this.data.LinkName,
        ComName: this.data.ComName
      }
    }
    app.getDaoPostN(url, params, function(r){
      if(r.code == 200){
        if(r.data == '1'){
          _this.setData({
            show: true,
          })
        }
        let page = 'doc'
        const env = {
          develop: 'cn',
          trial: 'cn',
          release: 'com'
        }
        _this.qyssdkcb(page, r.data, env[__wxConfig.envVersion])
        wx.hideLoading();
      }else{
        wx.hideLoading();
        wx.showToast({
          title: r.message,
          icon:'none'
        })
      }
    })
  },

  // 签署合同回调
  qyssdkcb(page, ticket, env){
    let eventChannel = null;
    const _this=this
    wx.navigateTo({
        url: `plugin://qyssdk-plugin/${page}?ticket=${ticket}&env=${env}&hasCb=true`,
        events: {
            signSuccessCb: () => { // 签署成功回调
              _this.updateInfo()
            }
        },
        success(res) {
            eventChannel = res.eventChannel;
        },
    });
  },
 
  // 更新用户信息
  updateInfo(){
    const url = 'api/FeijiuApp/Feijiu_HeZuo_UpdateUserInfo'
    const LoginUID = wx.getStorageSync('FjLoginLog').UID
    let params;
    if(this.data.utype == 1){
      params = {
        LoginUID,
        utype: this.data.utype,
        LinkMan: this.data.LinkName,
      }
    } else {
      params = {
        LoginUID,
        utype: this.data.utype,
        LinkMan: this.data.LinkName,
        ComName: this.data.ComName
      }
    }
    const _this=this
    app.getDaoPostN(url, params,function(r){
      if(r.code == 200){
        wx.showModal({
          title: '提示',
          // content: '合同签署成功！快来设置您的回收偏好~',
          // cancelText: '下载合同',
          // confirmText: '设置偏好',
          content: '合同签署成功!',
          confirmText: '下载合同',
          confirmColor: '#0cc783',
          success (res) {
            if (res.confirm) {
              _this.downloadContract()
              // _this.setPreferences()
            } else if (res.cancel) {
              _this.cancel()
              // _this.downloadContract()
            }
          }
        })
      }else{
        wx.showToast({
          title: r.message,
          icon:'none'
        })
      }
    })
  },

  // 下载合同获取下载地址 
  downloadContract(){
    const _this = this
    const LoginUID = wx.getStorageSync('FjLoginLog').UID
    const url = 'api/FeijiuApp/Feijiu_HeZuo_DownContract'
    app.getDaoPostN(url, {LoginUID},function(r){
      if(r.code == 200){
        wx.hideLoading();
        _this.download(r.data)
      }else{
        wx.hideLoading();
        wx.showToast({
          title: r.message,
          icon:'none'
        })
      }
    })
  },
  // 下载方法
  download(url){
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    // 获取后缀
    let index = url.lastIndexOf('.')
    let filttype = url.slice(index + 1)

    wx.downloadFile({ //下载
      url: url, // 从后端获取的url地址，赋值在标签的data属性上
      success: function (res) {
        const tempFilePath = res.tempFilePath;
        wx.saveFile({ //保存文件到本地
          tempFilePath,
          success(res) {
            const savedFilePath = res.savedFilePath;
            wx.openDocument({ //新开页面打开文档
              filePath: savedFilePath,
              showMenu: true,
              flieType: filttype,
              success: function (res) {
                wx.hideLoading()
              },
              fail: function (err) {
                wx.hideLoading()
                wx.showToast({
                  title: '暂不支持预览',
                  icon:"none"
                })
              }
            });
          },
        })
      },
      fail: function (err) {
        wx.showToast({
          title: '下载失败',
        })
      }
    })
  },
  // 设置回收偏好
  setPreferences(){
    wx.reLaunch({
      url: '/packageB/pages/assetsDisposal/CSExecutive'
    })
    // wx.reLaunch({
    //   url: '/pageB/pages/recycling/preferences'
    // });
  },
})